( function ($) { 
    $(document).ready(function(){

        function api( data, rfn ) {
            $.ajax({
                url: '/api/',
                type: 'POST',
                data: data,
                success: function(rdata){
                    if ((rdata.substr(0,1) == '{') || (rdata.substr(0,1) == '[')) rdata = JSON.parse(rdata);
                    if (rfn) {
                        rfn(rdata);
                    }
                },
                error: function(xhr, ajaxOptions, thrownError){
                    if (xhr.status == 0) { rfn({result:'timeout'}); }
                }
            });
        }

        
        /* Notifications */

        function notify( message, classes, msec ) {
            var el = $('<div class="'+classes+'">'+message+'</div>');
            $('.info-box').prepend(el);
            if ( msec )
            setTimeout(function(){
                $(el).fadeOut(msec, function(){
                    $(el).remove();
                });
            }, msec);
        }


        /* Translations */

        function __( str, context = 'default' ) {
            if (!soc) return str;
            if (!soc.locale) return str;
            if (!soc.translate[soc.locale][context][str]) return str;
            return soc.translate[soc.locale][context][str];
        }

        /* Fix checkbox */

        var $public = $('[data-new-post-public]').attr('checked');
        if ( $public ) {
            $('[data-new-post-public]').prop('checked',true);
        }

        /* Append editor */

        $('body').append('<script src="/js/jquery.form.min.js"></script>\
        <script src="/js/medium-editor.min.js"></script>\
        <link rel="stylesheet" href="/css/medium-editor.min.css">\
        <link rel="stylesheet" href="/css/themes/default.min.css">');
        
        /* data-translate-text */
        
        $('[data-new-post] [data-translate-text]').each(function(i,el){
            var text = $(el).text();
            text = __(text);
            $(el).text(text);
        });
        
    
        /* Кнопка создания поста */

        $('[data-new-post-btn]').click(function(){
            var data = {
                fn:      'save_post',
                title:   $('[data-new-post-title]').val(),
                html:    $('[data-new-post-text]').html(),
                attrs:   $('[data-new-post-attrs]').val(),
                url:     $('[data-new-post-url]').val(),
                img:     $('[data-new-post-img]').val(),
                public:  $('[data-new-post-public]').prop('checked'),
            }
            api(data, function(r){
                if ( r.info_text ) {
                    notify( r.info_text, r.info_class, r.info_time );
                }
                if (r.result == 'timeout') {
                    notify( __("Connection lost"), 'info-error', 10000 );
                }
                if ( window.location.pathname != '/edit'+r.url ) {
                    window.location.pathname = '/edit'+r.url;
                    //$('[data-new-post-url]').val(r.url);
                }
            });
        });

        /* Загрузка файлов */

        $('[data-upload-form] input[type=file]').change(function(){
            var bar     = $('.bar');
            var percent = $('.percent');
            var status  = $('#status');
            $('[data-upload-form]').ajaxSubmit({
                beforeSend: function() {
                    status.empty();
                    var percentVal = '0%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                uploadProgress: function(event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                success: function() {
                    var percentVal = '100%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                complete: function(xhr) {
                    if ( xhr.status == 200 ) {
                        if ((xhr.responseText.substr(0,1) == '{') || (xhr.responseText.substr(0,1) == '[')) {
                            r = JSON.parse(xhr.responseText);
                        }

                        if ( r.info_text ) {
                            notify( r.info_text, r.info_class, r.info_time );

                            if ( r.info_class == 'info-success' ) {

                                if ( r.url && $('[data-new-post-url]').val() == '' ) {
                                    $('[data-new-post-url]').val( r.url );
                                }
                                
                                if (r.flist) {
                                    for (var f in r.flist) {
                                        if ( r.flist[f].match(/\.(jpg|png)$/) ) {
                                            $('[data-new-post-text]').append('<img src="'+r.flist[f]+'"><p></p>');
                                        } else {
                                            $('[data-new-post-text]').append('<p>'+__('File')+' <a href="'+r.flist[f]+'">'+f+'</a> </p>');
                                        }
                                    }
                                }

                            }
                        }

                    } else {
                        notify( xhr.responseText, 'info-error', 0 );
                    }
                }
            });
            return false;
        });

        var editor = new MediumEditor('.editable');
        $('[data-new-post] .title').attr('placeholder', __('Title'));
        $('[data-new-post] div.medium-editor-element').attr('data-placeholder', __('Text'));

    }); 
})( jQuery );